<template>
  <div class="artice-list">
    <van-pull-refresh
      v-model="refreshLoading"
      @refresh="getNextPageArticle"
      success-text="刷新成功"
    >
      <van-list
        v-model="loading"
        @load="getNextPageArticle"
        :immediate-check="false"
        :finished="finished"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        finished-text="没有更多"
      >
        <article-item
          v-for="(item, index) in articls"
          :key="index"
          :article-info="item"
       
        >
        </article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 引入文张列表请求方法
import { getArticlesAPI } from '@/api'
// 文章列表在抽离成一个组件
import ArticleItem from './/ArticleItem.vue'

// list 组件的属性
// immediate-check 默认值是true，页面一加载就执行一次load事件



export default {
  // 子组件props可以是小驼峰，父组件传参可以是小驼峰或-
  name: 'ArticleList',
  data() {
    return {
      articls: [],
      loading: false,
      preTimestamp: '',
      error: false,
      finished: false,
      refreshLoading: false
    }
  },
  components: {
    ArticleItem
  },
  props: {
    channelId: [String, Number] // 数字或字符串
  },
  created() {
    this.getFirstPageArticle() // 页面一打开请求数据
  },
  //获取第一页文章列表函数
  methods: {
    async getFirstPageArticle() {
      try {
        const { data } = await getArticlesAPI(this.channelId, +new Date())
        //  console.log(data)
        this.articls = data.data.results
        // 当前下一页的数据
        this.preTimestamp = data.data.pre_timestamp
      } catch (error) {
        if (error.response?.status === 400) {
          // 如果是axios错误，并且状态码是400
          this.$toast.fail(error.response.data.message)
        } else {
          // 如果是js或状态码500
          throw error
        }
      }
    },
    async getNextPageArticle() {
      try {
        if (Math.random() < 0.5) {
          throw new Error()
        }
        //1.发送请求
        const { data } = await getArticlesAPI(this.channelId, this.preTimestamp)
        //2。添加数据
        const results = data.data.results
        this.articls.push(...results)

        if (this.loading) {
          this.articls = [...this.articls, ...results]
        } else {
          this.articls = [...results, ...this.articls]
        }
        //3。更新时间搓
        this.preTimestamp = data.data.pre_timestamp
        //4.判断是否加载完毕
        if (data.data.pre_timestamp === null) {
          this.finished = true
        }
      } catch (error) {
        this.error = true
      } finally {
        //5.手动将loading改为false
        this.loading = false
        this.refreshLoading = false
      }
    },
   
  }
}
</script>

<style scoped lang="less">
.artice-list {
  height: calc(100vh - 100px - 92px - 83px);
  overflow: auto;
  &::-webkit-scrollbar {
    width: 10px;
    background-color: transparent;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #3296fa;
    border-radius: 10px;
  }
}
</style>
